<template>
    <div class="map-search">
        <div class="map-filter">
            <input v-model="freetext" type="text" placeholder="在此输入  题名/责任者/出版地/出版社/出版年/主题词">
            <div class="tips" id="polygonChange">{{tipsChange?'鼠标绘制多边形进行检索':'双击鼠标完成绘制'}}</div>
        </div>
        <div class="map-box">
            <div id="container"></div>
            <!-- <div class="ctrl">
                <button type="button">清除选中区域</button>
            </div> -->
        </div>
        <a-modal v-model="visibleUser" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="login">
            <template slot="footer"><a-button key="submit" type="primary" @click="ConfirmError">确认</a-button></template>
            <p class="failure">获取用户信息出错，请联系管理员！</p>
        </a-modal>
        <a-modal v-model="visibleLook" :closable="false" :keyboard="false" :maskClosable="false" width="20%" title="消息" @ok="logout">
            <template slot="footer"><a-button key="submit" type="primary" @click="logout">确认</a-button></template>
            <p class="failure">您无权访问此站点！</p>
        </a-modal>
    </div>
</template>

<script>
    import axios from 'axios'
    import { accountAuthtication } from '../../api/urls';
    export default {
        data(){
            return{
                freetext: '',
                tipsChange:true,
                visibleUser: false,
                visibleLook: false,
                pageth: 1,
            }
        },

        created() {
            this.checkUser()
        },

        mounted() {
            this.mapInit()
        },

        methods: {
            async checkUser() {
                this.$parent.$parent.spinner = true
                /* 
                判断是否有传入token
                登录：https://www.cnbksy.com/jdLogin?targetUrl=https://tushu.cnbksy.com?ss
                返回token：https://jdts.library.sh.cn/?ss&token=6fd70427739110ab86b4a2f427423bb2e0c1cc2707665536f676fb4dda7a7ff6af8503d1c564ea39f86392a3848ec58ee7590403f3aee5947c0f9838e5f61396#/
                router(路由配置) 需修改为 mode: 'history' 模式
                通过 this.$route.query.xxx 获取
                */
                if(!sessionStorage.getItem('token')) {
                    sessionStorage.setItem('token', this.$route.query.token||'')
                }
                if(sessionStorage.getItem('token')&&!sessionStorage.getItem('orgName')) {
                    await axios.post(`${accountAuthtication}?token=`+ sessionStorage.getItem('token')).then(response => {
                        // debugger
                        if (response.data.result==0) {
                            this.$parent.$parent.$refs.header.orgName = response.data.data.username
                            sessionStorage.setItem('orgName', response.data.data.username)
                            this.$router.push({name: 'mapSearch'})
                        } else {
                            this.visibleUser = true
                        }
                    });
                }
                if(sessionStorage.getItem('token')&&sessionStorage.getItem('orgName')) {
                    this.$router.push({name: 'mapSearch'})
                }
                this.$parent.$parent.spinner = false
            },

            login() {
                window.location = 'https://dhapi.library.sh.cn/management/webapi/cenofmagent/token/locpage?systemId=20&durl=https://jdts.library.sh.cn/index'
            },

            async logout() {
                this.$parent.$parent.spinner = true
                this.visibleLook = false
                sessionStorage.setItem('token', '')
                sessionStorage.setItem('orgName', '')
                this.$router.push({
                    name: 'mapSearch'
                })
                location.reload()
            },

            ConfirmError(){
                this.visibleUser = false
            },
            quit() {
                window.opener = null;
                window.open("about:blank", "_self").close()
            },

            mapInit() {
                let that = this
                var cluster
                var map = new AMap.Map('container',{
                    zoom: 6,
                    resizeEnable: true,
                    center: [113.778584,34.759197],
                });
                AMap.plugin(['AMap.ToolBar','AMap.Scale','AMap.OverView','AMap.MarkerClusterer'],function(){
                    map.addControl(new AMap.ToolBar());//工具条
                    map.addControl(new AMap.Scale());//比例尺
                    cluster = new AMap.MarkerClusterer(map, new AMap.Marker(),{gridSize:80});//点聚合
                    var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0,-30)});
                    var mouseTool = new AMap.MouseTool(map);//在地图中添加MouseTool插件

                    // "民国图书"列表
                    function getMGTSList(e, mark, map) {
                        // 请求地址
                        // fetch('api/place?placeUri='+mark.uri+'&freetext='+that.freetext+"&pageth="+that.pageth,{method: "GET"})
                        fetch('https://jdts.library.sh.cn/mgts/mgts/place?placeUri='+mark.uri+'&freetext='+that.freetext+"&pageth="+that.pageth,{method: "GET"})
                        .then((response) => response.json()) // 取数据
                        .then((responseText) => { // 处理数据
                            // 重新渲染界面
                            let genealogyTitle = responseText.data.resultList;
                            let pageCount = responseText.data.pager.pageCount;
                            let rowCount = responseText.data.pager.rowCount;
                            let div = $("<div><p style='color:#333;font-size:16px;border-bottom:1px solid #eee;margin-bottom:0.5em;'>" + mark.label + "（" + rowCount + "本）" + "</p><p style='border-top:1px solid #eee; margin-top:1em; margin-bottom:0;'><a id='prev' style='color:#333;'>上一页</a>---<span style=font-weight:bolder;color:#2D64CD;>" + that.pageth + "/" + pageCount + "</span>---<a id='next' style='color:#333;'>下一页</a></p></div>");
                            if (genealogyTitle.length) {
                            for (let i = 0; i < genealogyTitle.length; i++) {
                                div.find('#prev').parent().before($("<a href='https://jdts.library.sh.cn/instanceDetail?uri=" + genealogyTitle[i].uri + "' target='_blank' style='display: block;'>" + (genealogyTitle[i].title?genealogyTitle[i].title:"Unknown") + "</a>"));
                            }
                            } else {
                            div.find('#prev').parent().before($("<span style='color: black'>No Data</span>"));
                            }
                            // 上一页操作
                            div.find('#prev').on('click', function(){
                            if(that.pageth-1 < 1) {
                                that.$message.error("已经是第一页了");
                            } else {
                                that.pageth = that.pageth-1
                                getMGTSList(e, mark, map)
                            }
                            })
                            // 下一页操作
                            div.find('#next').on('click', function(){
                            if(that.pageth+1 > pageCount) {
                                that.$message.error("已经是最后页了");
                            } else {
                                that.pageth = that.pageth+1
                                getMGTSList(e, mark, map)
                            }
                            })
                            infoWindow.setContent(div[0]);
                            infoWindow.open(map, e.target.getPosition());
                        })
                    }

                    // 鼠标绘制多边
                    function drawPolygon(map,cluster){
                        // 点击按钮是否绘制多边形和鼠标变化
                        AMap.event.addDomListener(document.getElementById("polygonChange"), 'click', function() {
                            // 判断是否需要绘制地图
                            if(that.tipsChange){
                                mouseTool.polygon(); //用鼠标工具画多边形
                                map.setDefaultCursor("crosshair");
                                that.tipsChange = false;
                                map.clearMap();
                                cluster.clearMarkers();
                                let markers=[];
                                // 绘制完成双击操作
                                var draw=AMap.event.addListener( mouseTool,'draw',function(e){ //添加事件
                                    let path=e.obj.getPath(),str='';//获取路径
                                    // 处理获取的路径数据
                                    for(let i=0;i<path.length;i++){
                                        str +=path[i].R+' '+path[i].Q+',';
                                    }
                                    str=str.substring(0,str.length-1);
                                    mouseTool.close(true);//移除鼠标事件
                                    map.setDefaultCursor("hand");
                                    AMap.event.removeListener(draw);//移除绘制事件
                                    // 获取路径内部的书目数据
                                    // fetch('api/map?points=POLYGON(('+str+'))&freetext='+that.freetext,{// 请求地址
                                    fetch('https://jdts.library.sh.cn/mgts/mgts/map?points=POLYGON(('+str+'))&freetext='+that.freetext,{// 请求地址
                                        method: "GET"
                                    })
                                    .then((response) => response.json()) // 取数据
                                    .then((responseText) => {// 处理数据
                                        // 重新渲染界面
                                        let marks='';
                                        marks=responseText.data;
                                        for(let j=0;j<marks.length;j++){
                                            let long,lat;
                                            long = (Math.random()/100)+parseFloat(marks[j].long);
                                            lat = (Math.random()/100)+parseFloat(marks[j].lat);
                                            let marker=new AMap.Marker({
                                                position: [long,lat],
                                                title: marks[j].label,
                                                offset: new AMap.Pixel(10,10), // 设置点标记偏移量
                                            });
                                            markers.push(marker);
                                            //给Marker绑定单击事件
                                            marker.on('click',function(e){
                                                that.pageth = 1
                                                getMGTSList(e, marks[j], map)
                                            });
                                        }
                                        cluster.setMarkers(markers);
                                    })  
                                    .catch((error) => {  
                                        console.log(error);
                                    });
                                    that.tipsChange = true;
                                    map.setDefaultCursor("hand");
                                    mouseTool.close(true);
                                });
                            }
                        });
                    }

                    drawPolygon(map,cluster);
                });
            },

        },

    }
</script>

<style lang="less" scoped>
    .ant-btn-primary {
		background-color: #661112;
		border-color: #661112;
	}
    .map-search{
        width: 94%;
        margin: 0 auto;
        max-width: 1140px;
        font-size: 1rem;
        .map-box{
            position: relative;
            width: 100%;
            height: calc(100vh - 180px);
            border: 1px solid #ddd;
            #container{
                width: 100%;
                height: calc(100vh - 180px);
            }
            .ctrl{
                position: absolute;
                bottom: 10px;
                right: 10px;
                width: 120px;
                height: 34px;
                button{
                    display: block;
                    width: 120px;
                    height: 34px;text-align: center;
                    line-height: 32px;
                    border-radius: 17px;
                    color: #fff;
                    background: #00a9e3;
                }
            }
        }
        .map-filter{
            display: flex;
            justify-content: space-between;
            padding: 8px 15px;
            background: #126e82;
            align-items: center;
            input{
                flex-grow: 1;
                background: #fff;
                height: 36px;
                line-height: 36px;
                padding-left: 10px;
                border-radius: 18px;
            }
            .tips{
                width: 250px;
                height: 34px;
                color: #fff;
                text-align: center;
                line-height: 34px;
                background: #965248;
                border-radius: 5px;
                margin-left: 20px;
                cursor: pointer;
                user-select:none
            }
        }
    }
</style>
<style>
    /* .amap-info-content {
        max-height: 200px;
    } */
</style>